import { useState } from 'react';
import { useUnit } from 'effector-react';

import { $sensors, $sensorsCrossCount } from 'store';
import History from './components/History';
import CustomQueries from './components/CustomQueries';
import LedControl from './components/LedControl';
import { prepare } from './utils';

const SensorValuesTable = () => {
  const sensors = useUnit($sensors);
  const cross = useUnit($sensorsCrossCount)
  const [onlyLast, setOnlyLast] = useState(true);

  const btnClasses = `btn btn-xs ${onlyLast && 'btn-success'}`;

  const onlyLastToggle = () => {
    setOnlyLast(!onlyLast);
  };

  return (
    <div className="overflow-x-auto">
      <button className={btnClasses} onClick={onlyLastToggle}>
        Only last values
      </button>

      <table className="table">
        <thead>
          <tr>
            <th>Ch2 №</th>
            <th>Ch3 №</th>
            <th>Серийный номер</th>
            <th>Дым/Температура</th>
            <th>Запрос</th>
            <th>Фонарь</th>
          </tr>
        </thead>

        <tbody>
          {sensors.map(
            (sensor, sensorIndex) => {
              const { seq2, seq3, sn, hist } = prepare(sensor)
              return (
                <tr key={sensorIndex}>
                  <td>{seq2}</td>
                  <td>{seq3}</td>
                  <td><code className="font-mono">{sn}</code></td>
                  <td><History history={hist} onlyLast={onlyLast} /></td>
                  <td><CustomQueries sensor={sensor} /></td>
                  <td><LedControl sensor={sensor} /></td>
                </tr>
              );
            }
          )}
        </tbody>

        <tfoot>
          <tr>
            <th>
              {cross?.crossCount2 && (cross.crossCount2 > 0) && (
                <>CrossCount: {cross.crossCount2}</>
              )}
            </th>
            <th>
              {cross?.crossCount3 && (cross.crossCount3 > 0) && (
                <>CrossCount: {cross.crossCount3}</>
              )}
            </th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
          </tr>
        </tfoot>
      </table>
    </div>
  );
};

export default SensorValuesTable;
